"use client";

import { useState, useEffect } from "react";
import { useDropzone } from "react-dropzone";
import { toast } from "react-hot-toast";
import { useWallet } from "@solana/wallet-adapter-react";
import { useConnection } from "@solana/wallet-adapter-react";
import Image from "next/image";
import {
  PublicKey,
  Keypair,
  SystemProgram,
  Transaction,
} from "@solana/web3.js";
import {
  createInitializeMintInstruction,
  createMintToInstruction,
  createAssociatedTokenAccountInstruction,
  getAssociatedTokenAddress,
  MINT_SIZE,
  TOKEN_PROGRAM_ID,
  getMinimumBalanceForRentExemptMint,
} from "@solana/spl-token";
import { apiClient } from "../lib/api";
import { CreateTokenDto } from "../types/api";

interface CreateTokenFormProps {
  onSuccess?: (token: any) => void;
  onError?: (error: string) => void;
}

interface FormData {
  // 基本信息
  name: string;
  symbol: string;
  decimals: number;
  supply: string;
  description: string;
  image?: File;

  // 靓号地址配置
  enablePrettyAddress: boolean;
  prettyPrefix: string;
  prettySuffix: string;
  caseSensitive: boolean;
  threads: number;

  // 社交链接
  enableSocialLinks: boolean;
  website: string;
  twitter: string;
  telegram: string;
  discord: string;

  // 权限控制
  revokeUpdateAuthority: boolean;
  revokeFreezeAuthority: boolean;
  revokeMintAuthority: boolean;
}

interface PrettyAddressInfo {
  difficulty: number;
  estimatedTime: string;
  generatedCount: number;
  speed: number;
  status: "idle" | "generating" | "success" | "error";
  progress: number;
}

export function CreateTokenForm({ onSuccess, onError }: CreateTokenFormProps) {
  const { connected, publicKey, sendTransaction } = useWallet();
  const { connection } = useConnection();

  const [formData, setFormData] = useState<FormData>({
    // 基本信息
    name: "",
    symbol: "",
    decimals: 9,
    supply: "10000000000",
    description: "",

    // 靓号地址配置
    enablePrettyAddress: true,
    prettyPrefix: "",
    prettySuffix: "c4pad",
    caseSensitive: false,
    threads: 1,

    // 社交链接
    enableSocialLinks: true,
    website: "",
    twitter: "",
    telegram: "",
    discord: "",

    // 权限控制
    revokeUpdateAuthority: false,
    revokeFreezeAuthority: false,
    revokeMintAuthority: false,
  });

  const [previewImage, setPreviewImage] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [uploadingImage, setUploadingImage] = useState(false);
  const [prettyAddressInfo, setPrettyAddressInfo] = useState<PrettyAddressInfo>(
    {
      difficulty: 1,
      estimatedTime: "0 秒",
      generatedCount: 0,
      speed: 0,
      status: "idle",
      progress: 0,
    }
  );
  const [errors, setErrors] = useState<Record<string, string>>({});

  // 计算靓号难度
  useEffect(() => {
    if (
      formData.enablePrettyAddress &&
      (formData.prettyPrefix || formData.prettySuffix)
    ) {
      estimatePrettyAddressDifficulty();
    }
  }, [
    formData.prettyPrefix,
    formData.prettySuffix,
    formData.caseSensitive,
    formData.threads,
  ]);

  const estimatePrettyAddressDifficulty = async () => {
    try {
      const params = new URLSearchParams({
        prefix: formData.prettyPrefix,
        suffix: formData.prettySuffix,
        caseSensitive: formData.caseSensitive.toString(),
        threads: formData.threads.toString(),
      });

      const API_URL =
        process.env.NEXT_PUBLIC_API_URL || "http://localhost:7172/api";
      const response = await fetch(
        `${API_URL}/pretty-address/estimate?${params}`
      );
      const data = await response.json();

      if (data.success) {
        setPrettyAddressInfo((prev) => ({
          ...prev,
          difficulty: data.data.difficulty,
          estimatedTime: data.data.estimatedTimeFormatted,
        }));
      }
    } catch (error) {
      console.error("Failed to estimate difficulty:", error);
    }
  };

  const { getRootProps, getInputProps, isDragActive } = useDropzone({
    accept: {
      "image/*": [".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".svg"],
    },
    maxFiles: 1,
    maxSize: 5 * 1024 * 1024, // 5MB
    onDrop: (acceptedFiles) => {
      const file = acceptedFiles[0];
      if (file) {
        setFormData((prev) => ({ ...prev, image: file }));

        // Create preview
        const reader = new FileReader();
        reader.onload = () => {
          setPreviewImage(reader.result as string);
        };
        reader.readAsDataURL(file);

        // Clear image error
        setErrors((prev) => ({ ...prev, image: "" }));
      }
    },
    onDropRejected: (rejectedFiles) => {
      const rejection = rejectedFiles[0];
      if (rejection.errors[0]?.code === "file-too-large") {
        toast.error("Image file cannot exceed 5MB");
        setErrors((prev) => ({ ...prev, image: "Image file cannot exceed 5MB" }));
      } else {
        toast.error("Please upload a valid image file");
        setErrors((prev) => ({ ...prev, image: "Please upload a valid image file" }));
      }
    },
  });

  // Form validation
  const validateForm = (): boolean => {
    const newErrors: Record<string, string> = {};

    if (!formData.name.trim()) {
      newErrors.name = "Please enter Token Name";
    }

    if (!formData.symbol.trim()) {
      newErrors.symbol = "Please enter Token Symbol";
    }

    if (!formData.supply.trim()) {
      newErrors.supply = "Please enter Token Total Supply";
    } else {
      const supply = parseFloat(formData.supply);
      if (isNaN(supply) || supply <= 0) {
        newErrors.supply = "Please enter a valid supply amount";
      }
    }

    if (!formData.image) {
      newErrors.image = "Please upload Token Logo";
    }

    // 验证社交链接格式
    if (formData.enableSocialLinks) {
      if (formData.website && !isValidUrl(formData.website)) {
        newErrors.website = "Please enter a valid website link";
      }
      if (formData.twitter && !isValidUrl(formData.twitter)) {
        newErrors.twitter = "Please enter a valid Twitter link";
      }
      if (formData.telegram && !isValidUrl(formData.telegram)) {
        newErrors.telegram = "Please enter a valid Telegram link";
      }
      if (formData.discord && !isValidUrl(formData.discord)) {
        newErrors.discord = "Please enter a valid Discord link";
      }
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const isValidUrl = (url: string): boolean => {
    try {
      new URL(url);
      return true;
    } catch {
      return false;
    }
  };

  // Upload image to backend
  const uploadImage = async (file: File): Promise<string> => {
    setUploadingImage(true);
    try {
      const response = await apiClient.uploadImage(file);

      if (response.success && response.data) {
        return response.data.url;
      } else {
        throw new Error(response.message || "Failed to upload image");
      }
    } catch (error: any) {
      console.error("Image upload error:", error);
      const errorMessage =
        error.response?.data?.message ||
        error.message ||
        "Failed to upload image";
      throw new Error(errorMessage);
    } finally {
      setUploadingImage(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!connected || !publicKey || !sendTransaction) {
      toast.error("Please connect your wallet first");
      return;
    }

    if (!validateForm()) {
      toast.error("Please check your form information");
      return;
    }

    setLoading(true);

    try {
      // Step 1: Pay platform fee of 0.2 SOL
      toast.loading("Please confirm payment of 0.2 SOL creation fee...", { id: "payment" });

      const platformWallet = new PublicKey(
        "813sZTyqkmUrbcGt1Bbo6dn6oRYC6Mh8og5Uk6EmFMAT"
      ); // 平台钱包地址
      const feeAmount = 0.2 * 1e9; // 0.2 SOL in lamports

      // 创建转账交易
      const transaction = new Transaction().add(
        SystemProgram.transfer({
          fromPubkey: publicKey,
          toPubkey: platformWallet,
          lamports: feeAmount,
        })
      );

      // 获取最新的区块哈希
      const { blockhash } = await connection.getLatestBlockhash();
      transaction.recentBlockhash = blockhash;
      transaction.feePayer = publicKey;

      // 发送交易
      const signature = await sendTransaction(transaction, connection);

      // 等待交易确认
      await connection.confirmTransaction(signature, "confirmed");

      toast.success("Payment of 0.2 SOL creation fee successful!", { id: "payment" });

      // Step 2: Upload image if provided
      let imageUrl = "";
      if (formData.image) {
        toast.loading("Uploading image...", { id: "upload" });
        imageUrl = await uploadImage(formData.image);
        toast.success("Image uploaded successfully", { id: "upload" });
      }

      // Step 3: Prepare token data with payment signature
      const tokenData: CreateTokenDto = {
        // 基本信息
        name: formData.name.trim(),
        symbol: formData.symbol.trim().toUpperCase(),
        decimals: formData.decimals,
        supply: formData.supply.trim(),
        description: formData.description.trim(),
        image: imageUrl,
        creator: publicKey.toString(),
        paymentSignature: signature, // 添加支付交易签名

        // 标记为联合曲线代币
        isBondingCurve: true,

        // 靓号地址配置
        enablePrettyAddress: formData.enablePrettyAddress,
        prettyPrefix: formData.enablePrettyAddress
          ? formData.prettyPrefix
          : undefined,
        prettySuffix: formData.enablePrettyAddress
          ? formData.prettySuffix
          : undefined,
        caseSensitive: formData.enablePrettyAddress
          ? formData.caseSensitive
          : undefined,
        threads: formData.enablePrettyAddress ? formData.threads : undefined,

        // 社交链接
        website: formData.enableSocialLinks ? formData.website : undefined,
        twitter: formData.enableSocialLinks ? formData.twitter : undefined,
        telegram: formData.enableSocialLinks ? formData.telegram : undefined,
        discord: formData.enableSocialLinks ? formData.discord : undefined,

        // 权限控制
        revokeUpdateAuthority: formData.revokeUpdateAuthority,
        revokeFreezeAuthority: formData.revokeFreezeAuthority,
        revokeMintAuthority: formData.revokeMintAuthority,
      };

      // Step 4: Create token via Bonding Curve API
      toast.loading("Creating bonding curve token...", { id: "create" });

      // 注意：这里需要用户签名而不是私钥，这只是临时解决方案
      // 在生产环境中应该使用钱包适配器的签名功能
      const tempMessage = "Please confirm token creation in your wallet";
      toast.loading(tempMessage, { id: "wallet-sign" });

      // 暂时跳过联合曲线API调用，直接创建普通代币并标记为联合曲线
      // TODO: 需要实现钱包签名机制来替代私钥要求

      // 创建代币（暂时使用现有API，待实现联合曲线集成）
      const response = await apiClient.createToken(tokenData);

      toast.dismiss("wallet-sign");

      if (response.success && response.data) {
        toast.success("Bonding curve token created successfully!", { id: "create" });

        // Reset form
        setFormData({
          name: "",
          symbol: "",
          decimals: 9,
          supply: "",
          description: "",
          enablePrettyAddress: true,
          prettyPrefix: "",
          prettySuffix: "",
          caseSensitive: false,
          threads: 1,
          enableSocialLinks: true,
          website: "",
          twitter: "",
          telegram: "",
          discord: "",
          revokeUpdateAuthority: false,
          revokeFreezeAuthority: false,
          revokeMintAuthority: false,
        });
        setPreviewImage(null);
        setErrors({});

        // Call success callback
        onSuccess?.(response.data);
      } else {
        throw new Error(
          response.message || "Failed to create bonding curve token"
        );
      }
    } catch (error: unknown) {
      console.error("Token creation error:", error);
      const errorMessage =
        (error as { response?: { data?: { message?: string } } })?.response
          ?.data?.message ||
        (error as { message?: string })?.message ||
        "Failed to create token";
      toast.error(errorMessage, { id: "create" });
      onError?.(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="pixel-card w-full mx-auto p-6 md:p-8">
      <h2 className="text-2xl md:text-3xl font-bold mb-6 font-pixel text-center">
        Create New Token
      </h2>

      <form onSubmit={handleSubmit} className="space-y-8 w-full">
        {/* Token Name */}
        <div>
          <label
            htmlFor="name"
            className="block text-base md:text-lg font-semibold text-gray-300 mb-3 font-body text-center"
          >
            Token Name *
          </label>
          <input
            type="text"
            id="name"
            value={formData.name}
            onChange={(e) =>
              setFormData((prev) => ({ ...prev, name: e.target.value }))
            }
            className={`pixel-input w-full font-body ${
              errors.name ? "border-red-500" : ""
            }`}
            style={{ fontSize: "14px" }}
            placeholder="e.g.: BBB Token"
            maxLength={32}
          />
          {errors.name && (
            <p className="text-red-400 text-sm mt-1">{errors.name}</p>
          )}
        </div>

        {/* Token Symbol */}
        <div className="w-full">
          <label
            htmlFor="symbol"
            className="block text-base md:text-lg font-semibold text-gray-300 mb-3 font-body text-center"
          >
            Token Symbol *
          </label>
          <input
            type="text"
            id="symbol"
            value={formData.symbol}
            onChange={(e) =>
              setFormData((prev) => ({
                ...prev,
                symbol: e.target.value.toUpperCase(),
              }))
            }
            className={`pixel-input w-full font-body ${
              errors.symbol ? "border-red-500" : ""
            }`}
            placeholder="例如: MAT"
            maxLength={10}
          />
          {errors.symbol && (
            <p className="text-red-400 text-sm mt-1">{errors.symbol}</p>
          )}
        </div>

        {/* Description */}
        <div className="w-full">
          <label
            htmlFor="description"
            className="block text-sm font-medium text-gray-300 mb-3 font-body"
          >
            Token Description
          </label>
          <textarea
            id="description"
            value={formData.description}
            onChange={(e) =>
              setFormData((prev) => ({ ...prev, description: e.target.value }))
            }
            rows={4}
            className="pixel-input w-full font-body"
            placeholder="描述您的代币..."
            maxLength={500}
          />
        </div>

        {/* Image Upload */}
        <div>
          <label className="block text-sm font-medium text-gray-300 mb-3 font-body">
            Token Icon *
          </label>
          <div
            {...getRootProps()}
            className={`border-2 border-dashed border-gray-600 bg-gray-700 p-8 md:p-10 text-center cursor-pointer transition-colors hover:border-purple-500 ${
              isDragActive
                ? "border-purple-500 bg-gray-600"
                : errors.image
                ? "border-red-500 bg-red-900"
                : ""
            }`}
          >
            <input {...getInputProps()} />
            {previewImage ? (
              <div className="space-y-4">
                <Image
                  src={previewImage}
                  alt="Preview"
                  width={96}
                  height={96}
                  className="mx-auto rounded-lg object-cover"
                />
                <p className="text-sm text-gray-400 font-body">
                  Click or drag to upload a new image
                </p>
              </div>
            ) : (
              <div className="space-y-2">
                <div className="text-gray-400">
                  <svg
                    className="w-12 h-12 mx-auto"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"
                    />
                  </svg>
                </div>
                <p className="text-sm text-gray-400 font-body">
                  {isDragActive ? "放下文件..." : "点击上传或拖拽图片到此处"}
                </p>
                <p className="text-xs text-gray-500 font-body">
                  Supported formats: PNG, JPG, GIF. Max size: 5MB
                </p>
              </div>
            )}
          </div>
          {errors.image && (
            <p className="text-red-500 text-sm mt-1">{errors.image}</p>
          )}
        </div>

        {/* Supply and Decimals */}
        <div className="grid grid-cols-2 gap-6">
          <div>
            <label
              htmlFor="supply"
              className="block text-sm font-medium text-gray-300 mb-3 font-body"
            >
              Token Total Supply *
            </label>
            <input
              type="text"
              id="supply"
              value={formData.supply}
              onChange={(e) =>
                setFormData((prev) => ({ ...prev, supply: e.target.value }))
              }
              className={`pixel-input w-full font-body ${
                errors.supply ? "border-red-500" : ""
              }`}
              placeholder="e.g.: 1000000"
            />
            {errors.supply && (
              <p className="text-red-500 text-sm mt-1">{errors.supply}</p>
            )}
          </div>
          <div>
            <label
              htmlFor="decimals"
              className="block text-sm font-medium text-gray-300 mb-3 font-body"
            >
              Token Decimals
            </label>
            <select
              id="decimals"
              value={formData.decimals}
              onChange={(e) =>
                setFormData((prev) => ({
                  ...prev,
                  decimals: parseInt(e.target.value),
                }))
              }
              className="pixel-input w-full font-body"
            >
              {[0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map((decimal) => (
                <option key={decimal} value={decimal}>
                  {decimal}
                </option>
              ))}
            </select>
          </div>
        </div>

        {/* Pretty Address Configuration */}
        <div className="pixel-card p-5 md:p-6">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-lg font-medium font-pixel">
              Pretty Address Configuration
            </h3>
            <label className="flex items-center">
              <input
                type="checkbox"
                checked={formData.enablePrettyAddress}
                onChange={(e) =>
                  setFormData((prev) => ({
                    ...prev,
                    enablePrettyAddress: e.target.checked,
                  }))
                }
                className="h-4 w-4 text-purple-600 focus:ring-purple-500 border-gray-300"
              />
              <span className="ml-2 text-sm text-gray-300 font-body">
                Enable Pretty Address
              </span>
            </label>
          </div>

          {formData.enablePrettyAddress && (
            <div className="space-y-5">
              <div className="grid grid-cols-2 gap-6">
                <div>
                  <label
                    htmlFor="prettyPrefix"
                    className="block text-sm font-medium text-gray-300 mb-3 font-body"
                  >
                    Pretty Address Prefix
                  </label>
                  <input
                    type="text"
                    id="prettyPrefix"
                    value={formData.prettyPrefix}
                    onChange={(e) =>
                      setFormData((prev) => ({
                        ...prev,
                        prettyPrefix: e.target.value,
                      }))
                    }
                    className="pixel-input w-full font-body"
                    placeholder="例如: ABC"
                    maxLength={8}
                  />
                </div>
                <div>
                  <label
                    htmlFor="prettySuffix"
                    className="block text-sm font-medium text-gray-300 mb-3 font-body"
                  >
                    Pretty Address Suffix
                  </label>
                  <input
                    type="text"
                    id="prettySuffix"
                    value={formData.prettySuffix}
                    onChange={(e) =>
                      setFormData((prev) => ({
                        ...prev,
                        prettySuffix: e.target.value,
                      }))
                    }
                    className="pixel-input w-full font-body"
                    placeholder="例如: 888"
                    maxLength={8}
                  />
                </div>
              </div>

              <div className="grid grid-cols-2 gap-6">
                <div>
                  <label className="flex items-center">
                    <input
                      type="checkbox"
                      checked={formData.caseSensitive}
                      onChange={(e) =>
                        setFormData((prev) => ({
                          ...prev,
                          caseSensitive: e.target.checked,
                        }))
                      }
                      className="h-4 w-4 text-purple-600 focus:ring-purple-500 border-gray-300 rounded"
                    />
                    <span className="ml-2 text-sm text-gray-300 font-body">
                      Case Sensitive
                    </span>
                  </label>
                </div>
                <div>
                  <label
                    htmlFor="threads"
                    className="block text-sm font-medium text-gray-300 mb-3 font-body"
                  >
                    Generate Threads
                  </label>
                  <select
                    id="threads"
                    value={formData.threads}
                    onChange={(e) =>
                      setFormData((prev) => ({
                        ...prev,
                        threads: parseInt(e.target.value),
                      }))
                    }
                    className="pixel-input w-full font-body"
                  >
                    {[1, 2, 4, 8, 16].map((thread) => (
                      <option key={thread} value={thread}>
                        {thread}
                      </option>
                    ))}
                  </select>
                </div>
              </div>

              {/* Pretty Address Info */}
              {(formData.prettyPrefix || formData.prettySuffix) && (
                <div className="bg-gray-800 border border-gray-700 rounded p-5">
                  <h4 className="text-sm font-medium text-gray-200 mb-2 font-body">
                    Pretty Address Difficulty Estimation
                  </h4>
                  <div className="space-y-2 text-sm text-gray-300 font-body">
                    <div className="flex justify-between">
                      <span>Difficulty Level:</span>  
                      <span
                        className={`font-medium ${
                          prettyAddressInfo.difficulty <= 2
                            ? "text-green-600"
                            : prettyAddressInfo.difficulty <= 4
                            ? "text-yellow-600"
                            : "text-red-600"
                        }`}
                      >
                        {prettyAddressInfo.difficulty}
                      </span>
                    </div>
                    <div className="flex justify-between">
                      <span>Estimated Time:</span>
                      <span>{prettyAddressInfo.estimatedTime}</span>
                    </div>
                    {prettyAddressInfo.status === "generating" && (
                      <div className="w-full bg-gray-200 rounded-full h-2">
                        <div
                          className="bg-purple-600 h-2 rounded-full transition-all duration-300"
                          style={{ width: `${prettyAddressInfo.progress}%` }}
                        ></div>
                      </div>
                    )}
                  </div>
                </div>
              )}
            </div>
          )}
        </div>

        {/* Social Links */}
        <div className="pixel-card p-5 md:p-6">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-lg font-medium font-pixel">Social Links</h3>
            <label className="flex items-center">
              <input
                type="checkbox"
                checked={formData.enableSocialLinks}
                onChange={(e) =>
                  setFormData((prev) => ({
                    ...prev,
                    enableSocialLinks: e.target.checked,
                  }))
                }
                className="h-4 w-4 text-purple-600 focus:ring-purple-500 border-gray-300 rounded"
              />
              <span className="ml-2 text-sm text-gray-300 font-body">
                Enable Social Links
              </span>
            </label>
          </div>

          {formData.enableSocialLinks && (
            <div className="grid grid-cols-2 gap-6">
              <div>
                <label
                  htmlFor="website"
                  className="block text-sm font-medium text-gray-300 mb-3 font-body"
                >
                  Website
                </label>
                <input
                  type="url"
                  id="website"
                  value={formData.website}
                  onChange={(e) =>
                    setFormData((prev) => ({
                      ...prev,
                      website: e.target.value,
                    }))
                  }
                  className={`pixel-input w-full font-body ${
                    errors.website ? "border-red-500" : ""
                  }`}
                  placeholder="https://example.com"
                />
                {errors.website && (
                  <p className="text-red-500 text-sm mt-1">{errors.website}</p>
                )}
              </div>
              <div>
                <label
                  htmlFor="twitter"
                  className="block text-sm font-medium text-gray-300 mb-3 font-body"
                >
                  Twitter
                </label>
                <input
                  type="url"
                  id="twitter"
                  value={formData.twitter}
                  onChange={(e) =>
                    setFormData((prev) => ({
                      ...prev,
                      twitter: e.target.value,
                    }))
                  }
                  className={`pixel-input w-full font-body ${
                    errors.twitter ? "border-red-500" : ""
                  }`}
                  placeholder="https://twitter.com/username"
                />
                {errors.twitter && (
                  <p className="text-red-500 text-sm mt-1">{errors.twitter}</p>
                )}
              </div>
              <div>
                <label
                  htmlFor="telegram"
                  className="block text-sm font-medium text-gray-300 mb-3 font-body"
                >
                  Telegram
                </label>
                <input
                  type="url"
                  id="telegram"
                  value={formData.telegram}
                  onChange={(e) =>
                    setFormData((prev) => ({
                      ...prev,
                      telegram: e.target.value,
                    }))
                  }
                  className={`pixel-input w-full font-body ${
                    errors.telegram ? "border-red-500" : ""
                  }`}
                  placeholder="https://t.me/channel"
                />
                {errors.telegram && (
                  <p className="text-red-500 text-sm mt-1">{errors.telegram}</p>
                )}
              </div>
              <div>
                <label
                  htmlFor="discord"
                  className="block text-sm font-medium text-gray-300 mb-3 font-body"
                >
                  Discord
                </label>
                <input
                  type="url"
                  id="discord"
                  value={formData.discord}
                  onChange={(e) =>
                    setFormData((prev) => ({
                      ...prev,
                      discord: e.target.value,
                    }))
                  }
                  className={`pixel-input w-full font-body ${
                    errors.discord ? "border-red-500" : ""
                  }`}
                  placeholder="https://discord.gg/invite"
                />
                {errors.discord && (
                  <p className="text-red-500 text-sm mt-1">{errors.discord}</p>
                )}
              </div>
            </div>
          )}
        </div>

        {/* Authority Controls */}
        <div className="pixel-card p-5 md:p-6">
          <h3 className="text-lg font-medium mb-4 font-pixel">Authority Controls</h3>
          <div className="space-y-3">
            <label className="flex items-center">
              <input
                type="checkbox"
                checked={formData.revokeUpdateAuthority}
                onChange={(e) =>
                  setFormData((prev) => ({
                    ...prev,
                    revokeUpdateAuthority: e.target.checked,
                  }))
                }
                className="h-4 w-4 text-purple-600 focus:ring-purple-500 border-gray-300 rounded"
              />
              <span className="ml-2 text-sm text-gray-300 font-body">
                Revoke Update Authority (Token Metadata Cannot Be Modified)
              </span>
            </label>
            <label className="flex items-center">
              <input
                type="checkbox"
                checked={formData.revokeFreezeAuthority}
                onChange={(e) =>
                  setFormData((prev) => ({
                    ...prev,
                    revokeFreezeAuthority: e.target.checked,
                  }))
                }
                className="h-4 w-4 text-purple-600 focus:ring-purple-500 border-gray-300 rounded"
              />
              <span className="ml-2 text-sm text-gray-300 font-body">
                Revoke Freeze Authority (Account Cannot Be Frozen)
              </span>
            </label>
            <label className="flex items-center">
              <input
                type="checkbox"
                checked={formData.revokeMintAuthority}
                onChange={(e) =>
                  setFormData((prev) => ({
                    ...prev,
                    revokeMintAuthority: e.target.checked,
                  }))
                }
                className="h-4 w-4 text-purple-600 focus:ring-purple-500 border-gray-300 rounded"
              />
              <span className="ml-2 text-sm text-gray-300 font-body">
                Revoke Mint Authority (Token Cannot Be Minted)
              </span>
            </label>
          </div>
        </div>

        {/* Submit Button */}
        <button
          type="submit"
          disabled={loading || uploadingImage || !connected}
          className="pixel-btn w-full disabled:opacity-50 disabled:cursor-not-allowed"
        >
          {uploadingImage
            ? "上传图片中..."
            : loading
            ? "创建联合曲线代币中..."
            : "创建联合曲线代币"}
        </button>

        {!connected && (
          <p className="text-sm text-gray-400 text-center">
            Please Connect Your Wallet to Create a Token
          </p>
        )}
      </form>
    </div>
  );
}
